#include "stdtypes.h"
#include "server.h"
#include "sys.h"

HANDLE pipe;
sys_event_t recv_ret;

static void cli_heart_thread(void *arg) {
    char *heart_beat = "hello";
    int w_size;
    while (1) {
        // LOG_DEBUG("send heart beat\n")
        // send_pipe_msg(pipe, 5, heart_beat);
        // sys_pipe_write(pipe, heart_beat, 5, &w_size);
        // LOG_INFO("heart send\n");
        Sleep(1000);
    }
}

// static void cli_recv_thread(void *arg) {
//     char *cli_buf = NULL;
//     int cli_len = 0;
//     int read_size;
//     while (1) {
//         sys_event_wait(recv_ret, -1);
//         read_size = recv_pipe_msg(pipe, (void **)&cli_buf, &cli_len);
//         if (cli_len > 0) {
//             mnet_printf("%s\n", cli_buf);
//         }
//         free(cli_buf);
//     }
// }

int get_input_length(unsigned char *buf) {
    int cnt = 0;
    while(buf[cnt] != '\0' && buf[cnt] != '\n' && buf[cnt] != '\r') {
        cnt++;
    }
    // LOG_DEBUG("user input len: %d\n", cnt);
    return cnt;
}

int main() {
    // 判断是否有可以利用的命名管道
    while (!sys_wait_pipe_create(CLI_PIPE))
    {
        LOG_ERROR("Pipe Not Accessible\n");
        Sleep(1000);
    }
    LOG_INFO("Pipe Is Live\n");
    pipe = sys_open_pipe(CLI_PIPE);
    if (pipe == INVALID_HANDLE_VALUE) {
        LOG_FATAL("Pipe Conn Fail\n");
        return 0;
    }
    LOG_INFO("Pipe Conn Success\n");
    unsigned char cli_buffer[512];
    unsigned char *send_msg = NULL;
    unsigned int write_size, read_size;
    char *cli_buf = NULL;
    int cli_len;
    recv_ret = sys_event_create(NULL);
    sys_thread_create(cli_heart_thread, (void *)0);
    // sys_thread_create(cli_recv_thread, (void *)0);
    int length;
    while (1) {
        mnet_printf(">>>[send]");
        fgets(cli_buffer, 512, stdin);
        length = get_input_length(cli_buffer);
        if (length == 0) continue;
        send_msg = malloc(length + 1);
        send_msg[length] = '\0';
        memcpy(send_msg, cli_buffer, length);
        // LOG_DEBUG("send msg:%s\n", send_msg);
        // sys_pipe_write(pipe, cli_buffer, 512, &write_size);
        send_pipe_msg(pipe, length + 1, send_msg);
        // sys_event_notify(recv_ret);
        if (memcmp(cli_buffer, "exit", 4) == 0) {
            LOG_WARNNING("Pipe dis conn\n");
            CloseHandle(pipe);
            return 0;
        }
        recv_pipe_msg(pipe, (void **)&cli_buf, &cli_len);
        if (cli_len > 0) {
            mnet_printf(">>>[recv]%s\n", cli_buf);
        }
        free(cli_buf);
        LOG_INFO("cmd exec success\n");
    }
}